package com.young.ysepay.mq;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.young.ysepay.utils.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * MQ消息处理类
 */


@Component
public class YsReturnMessageListener implements MessageListener {
    @Autowired
    private YsReportResult ysReportResult;

    public static final Logger logger = LoggerFactory.getLogger(YsReturnMessageListener.class);

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
       /* logger.error(new Date() + "MessageListenerImpl Receive message, Topic is:" + message.getTopic()
                + ", MsgId is:" + message.getMsgID()+",tags is:"+message.getTag());

        return Action.CommitMessage;*/

        //Topic校验Tag校验
        if (!message.getTopic().equals(YsReturnMQConfig.YS_TOPIC) || StringUtils.isEmpty(message.getTag())) {
            logger.error("Topic不符合订阅要求，Topic：" + message.getTopic() + "或者Tag为空，Tag：" + message.getTag());
            return Action.CommitMessage;
        }
        //获取消息重试次数
        int reconsume = message.getReconsumeTimes();
        if (reconsume == 3) {
            logger.error("该消息重复消费三次，直接标识成功");
            return Action.CommitMessage;

        }
        //解析消息体
        Map<String, Object> result = JSONUtils.jsonToMap(new String(message.getBody()));

        /**
         * 通过TAG来判断处理方式
         *
         */
        logger.info("获取消息：" + result.toString());
        boolean handleResult = true;
        if (YsReturnMQConfig.YSREQUERTREPORT.equals(message.getTag())) {
            logger.info("===========商户请求报备处理：============");
            handleResult = ysReportResult.dealSynResult(result);
            //积分支付回执处理
        }
        if (YsReturnMQConfig.YSREQUERTREPORTRESULTQUERY.equals(message.getTag())) {
            logger.info("===========商户报备结果查询：============");
            handleResult = ysReportResult.dealQueryResult(result);
            //积分支付回执处理
        }
        if (!handleResult) {
            logger.error("处理失败；Tag：" + message.getTag());
        }
        return Action.CommitMessage;
    }


}
